const multer = require('multer');
const fs = require('fs');
const path = require('path');

const isPackaged = process.pkg ? true : false;
let uploadPath;

if (isPackaged) {
  uploadPath = path.join(path.dirname(process.execPath), 'SKFiles');
} else {
  uploadPath = path.join(__dirname, '../SKFiles');
}

if (!fs.existsSync(uploadPath)) {
  fs.mkdirSync(uploadPath, { recursive: true });
  console.log('创建文件上传文件夹:', uploadPath);
}

// 配置 multer 上传
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    if (!fs.existsSync(uploadPath)) {
      try {
        fs.mkdirSync(uploadPath, { recursive: true });
        console.log('创建成功:', uploadPath);
      } catch (err) {
        console.error('创建失败', err.message);
        throw err;
      }
    }
    cb(null, uploadPath);
  },
  filename: (req, file, cb) => {
    const originalName = decodeURIComponent(file.originalname);
    cb(null, `${Date.now()}-${originalName}`);
  }
});

const upload = multer({
  storage: storage,
  limits: { fileSize: 500 * 1024 * 1024 },
  fileFilter: (req, file, cb) => {
    const allowedTypes = /jpeg|jpg|png|pdf|xlsx|xls|mp4/;
    const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = allowedTypes.test(file.mimetype) || 
                     file.mimetype === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                     file.mimetype === 'application/vnd.ms-excel';
    if (extname && mimetype) {
      return cb(null, true);
    }
    cb(new Error('不支持该文件类型!'));
  }
}).single('file');

// 上传文件
const uploadFile = (req, res) => {
  upload(req, res, (err) => {
    if (err) {
      return res.status(500).json({ success: false, code: '1', msg: err.message });
    }
    if (!req.file) {
      return res.status(500).json({ success: false, code: '1', msg: '未上传文件' });
    }
    try {
      const filePath = path.join(uploadPath, req.file.filename); // 使用 uploadPath
      res.json({ code: '0', filename: req.file.filename, path: filePath, msg: '文件上传成功' });
    } catch (err) {
      console.error('文件处理失败:', err.message);
      res.status(500).json({ success: false, code: '1', msg: '文件处理失败' });
    }
  });
};

// 下载文件
const downloadFile = (req, res) => {
  const { filename } = req.params;
  const filePath = path.join(uploadPath, filename); // 使用 uploadPath

  if (fs.existsSync(filePath)) {
    res.download(filePath, filename, (err) => {
      if (err) {
        console.error('文件下载失败:', err.message);
        res.status(500).json({ success: false, code: '1', msg: '下载失败' });
      }
    });
  } else {
    res.status(500).json({ success: false, code: '1', msg: '未找到文件' });
  }
};

// 文件删除
const deleteFile = (req, res) => {
  const { filename } = req.body;
  const decodedFilename = decodeURIComponent(filename);
  const filePath = path.join(uploadPath, decodedFilename); // 使用 uploadPath

  if (!fs.existsSync(filePath)) {
    return res.status(500).json({ success: false, code: '1', msg: '未找到文件' });
  }

  if (!filePath.startsWith(uploadPath)) {
    return res.status(500).json({ success: false, code: '1', msg: '没有删除权限' });
  }

  fs.unlink(filePath, (err) => {
    if (err) {
      console.error('Delete file error:', err.message);
      return res.status(500).json({ success: false, code: '1', msg: '删除失败' });
    }
    res.json({ success: true, code: '0', msg: '删除成功' });
  });
};

// 预览文件
const previewFile = (req, res) => {
  const { filename } = req.params;
  const decodedFilename = decodeURIComponent(filename);
  const filePath = path.join(uploadPath, decodedFilename); // 使用 uploadPath
  const ext = path.extname(decodedFilename).toLowerCase();

  if (!fs.existsSync(filePath)) {
    return res.status(500).json({ code: '1', success: false, msg: '未找到文件' });
  }

  if (!filePath.startsWith(uploadPath)) {
    return res.status(500).json({ code: '1', success: false, msg: '没有该文件预览权限' });
  }

  let contentType;
  switch (ext) {
    case '.jpg':
    case '.jpeg':
    case '.png':
      contentType = 'image/jpeg';
      break;
    case '.pdf':
      contentType = 'application/pdf';
      break;
    case '.mp4':
      contentType = 'video/mp4';
      break;
    case '.xlsx':
    case '.xls':
      contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      res.setHeader('Content-Disposition', 'attachment; filename="' + encodeURIComponent(decodedFilename) + '"');
      break;
    default:
      return res.status(500).json({ code: '1', success: false, msg: '该文件类型不支持预览' });
  }
  res.setHeader('Content-Type', contentType);
  res.setHeader('Content-Disposition', 'inline; filename="' + encodeURIComponent(decodedFilename) + '"');
  fs.createReadStream(filePath).pipe(res);
};

module.exports = { uploadFile, downloadFile, deleteFile, previewFile };